package com.fzg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fzg.common.enums.ResponseWrapper;
import com.fzg.common.model.login.param.*;
import com.fzg.common.model.login.result.BackLoginResult;
import com.fzg.common.model.login.result.GetCurrentLoginRoleNameResult;
import com.fzg.common.model.login.result.ReceptionLoginResult;
import com.fzg.common.tool.ImageCodeTool;
import com.fzg.common.tool.JwtUtil;
import com.fzg.common.tool.MD5Tool;
import com.fzg.entity.Enterprise;
import com.fzg.entity.User;
import com.fzg.mapper.EnterpriseMapper;
import com.fzg.mapper.UserMapper;
import com.fzg.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * create by fzg
 * 2021/12/13 15:32
 */

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Override
    public ResponseWrapper backLogin(BackLoginParam param) {

        // 返回结果
        BackLoginResult backLoginResult = new BackLoginResult();

        if (param.getRoleAid()==1){
            // 管理员登陆 （由于表设计，管理员只有我一个，所以放在用户表里面）
            // 根据账号查询user表
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .eq(User::getIsAdmin,1) // 管理员
                    .eq(User::getAccountNumber, param.getAccount()));
            if (user == null){
                // 不存在该账号的管理员
                return ResponseWrapper.markCustomError("不存在这个账号的管理员，请重新输入账号！");
            }else {
                // 判断密码
                if (!user.getPassword().equals(MD5Tool.getMD5(param.getPassword()))){
                    // 密码错误
                    return ResponseWrapper.markCustomError("密码错误，请重新输入！");
                }else {
                    // 账号密码都正确，制作token
                    Map<String, String> map = new HashMap<>();
                    map.put("aid", user.getAid().toString());
                    String token = JwtUtil.getToken(map);
                    backLoginResult.setToken(token);
                    backLoginResult.setRoleAid(param.getRoleAid());
                    return ResponseWrapper.markCustomSuccess("登陆成功！",backLoginResult);
                }
            }
        }
        if (param.getRoleAid() == 2){
            // 根据账号查询user表
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .eq(User::getIsAdmin,0) // 不是管理员
                    .eq(User::getAccountNumber, param.getAccount()));
            if (user == null){
                // 不存在该账号的用户
                return ResponseWrapper.markCustomError("不存在这个账号的用户，请重新输入账号！");
            }else {
                // 判断密码
                if (!user.getPassword().equals(MD5Tool.getMD5(param.getPassword()))){
                    // 密码错误
                    return ResponseWrapper.markCustomError("密码错误，请重新输入！");
                }else {
                    // 账号密码都正确，制作token
                    Map<String, String> map = new HashMap<>();
                    map.put("aid", user.getAid().toString());
                    String token = JwtUtil.getToken(map);
                    backLoginResult.setToken(token);
                    backLoginResult.setRoleAid(param.getRoleAid());
                    return ResponseWrapper.markCustomSuccess("登陆成功！",backLoginResult);
                }
            }
        }
        if (param.getRoleAid() == 3){
            // 根据账号查询企业表
            Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, param.getAccount()));
            if (enterprise == null){
                // 不存在该账号的用户
                return ResponseWrapper.markCustomError("不存在这个账号的企业，请重新输入账号！");
            }else {
                // 判断密码
                if (!enterprise.getPassword().equals(MD5Tool.getMD5(param.getPassword()))){
                    // 密码错误
                    return ResponseWrapper.markCustomError("密码错误，请重新输入！");
                }else {
                    // 账号密码都正确，制作token
                    Map<String, String> map = new HashMap<>();
                    map.put("aid", enterprise.getAid().toString());
                    String token = JwtUtil.getToken(map);
                    backLoginResult.setToken(token);
                    backLoginResult.setRoleAid(param.getRoleAid());
                    return ResponseWrapper.markCustomSuccess("登陆成功！",backLoginResult);
                }
            }
        }
        return ResponseWrapper.markError();
    }

    @Override
    public ResponseWrapper getLoginInfo(String account) {
        if (account != null){
            // 查询用户表
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, account));
            if (user == null){
                // 登陆的不是用户，是企业
                // 查询公司表
                Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, account));
                return ResponseWrapper.markSuccess(enterprise.getName());
            }else {
                String name;
                if (user.getIsAdmin().equals(1)){
                    name = "管理员" + "(" + user.getName() + ")";
                    return ResponseWrapper.markSuccess(name);
                }else {
                    return ResponseWrapper.markSuccess(user.getName());
                }
            }
        }
        return ResponseWrapper.markError();
    }

    @Override
    public ResponseWrapper getReceptionLoginImageCode() {
        Map<String, Object> imageCodeMap = ImageCodeTool.getImageCode();
        return ResponseWrapper.markSuccess(imageCodeMap);
    }

    @Override
    public ResponseWrapper receptionLogin(ReceptionLoginParam param) {

        // 返回结果
        ReceptionLoginResult result = new ReceptionLoginResult();

        // 通过账号查询
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
        if (user==null){
            // 该账号不存在,查询企业表
            Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, param.getAccount()));
            if (enterprise == null){
                // 企业账号也不存在
                return ResponseWrapper.markCustomError("该账号不存在，请重新输入！");
            }else {
                // 企业账号存在，验证该账号的密码是否正确
                if (enterprise.getPassword().equals(MD5Tool.getMD5(param.getPassword()))){
                    // 密码正确，判断验证码是否正确
                    boolean isSimple = ImageCodeTool.imageCodeCheck(param.getImageCodeKey(), param.getImageCode());
                    if (isSimple){
                        // 验证码正确,判断角色
                        if (param.getRoleAid().equals(3)){
                            // 制作token
                            Map<String, String> map = new HashMap<>();
                            map.put("aid", enterprise.getAid().toString());
                            String token = JwtUtil.getToken(map);
                            result.setToken(token);
                            return ResponseWrapper.markCustomSuccess("登陆成功！",result);
                        }else {
                            // 角色不正确
                            return ResponseWrapper.markCustomError("不存在这个角色！");
                        }
                    }else {
                        // 验证码不正确
                        return ResponseWrapper.markCustomError("验证码错误！");
                    }
                }else {
                    // 密码不正确
                    return ResponseWrapper.markCustomError("密码错误！");
                }
            }
        }else {
            // 该用户存在，验证该账号的密码是否正确
            if (user.getPassword().equals(MD5Tool.getMD5(param.getPassword()))){
                // 密码正确，判断验证码是否正确
                boolean isSimple = ImageCodeTool.imageCodeCheck(param.getImageCodeKey(), param.getImageCode());
                if (isSimple){
                    // 验证码正确,判断角色
                    if ((param.getRoleAid().equals(1) && user.getIsAdmin().equals(1)) || param.getRoleAid().equals(2)){
                        // 制作token
                        Map<String, String> map = new HashMap<>();
                        map.put("aid", user.getAid().toString());
                        String token = JwtUtil.getToken(map);
                        result.setToken(token);
                        return ResponseWrapper.markCustomSuccess("登陆成功！",result);
                    }else {
                        // 角色不正确
                        return ResponseWrapper.markCustomError("不存在这个角色！");
                    }
                }else {
                    // 验证码不正确
                    return ResponseWrapper.markCustomError("验证码错误！");
                }
            }else {
                return ResponseWrapper.markCustomError("密码错误！");
            }
        }
    }

    @Override
    public ResponseWrapper receptionRegister(ReceptionRegisterParam param) {
        // 1. roleAid = 1 添加到用户表
        if (param.getRoleAid().equals(1)){
            // 用户注册
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>().orderByDesc(User::getAid).last("limit 1"));
            Integer addUserAid = user.getAid() + 1;
            userMapper.insert(new User(){{
                setAid(addUserAid);
                setName(param.getName());
                setPassword(MD5Tool.getMD5(param.getPassword()));
                setAccountNumber(param.getAccount());
                setPhone(param.getPhone());
                setEmail(param.getEmail());
                setGender(1);
                setIdentityNumber("未知");
                setMaritalStatus(0);
                setWorkExperience("无");
                setIsAdmin(0);
                setAddress("住址暂无");
                setAvatar("https://recruitment-files.oss-cn-chengdu.aliyuncs.com/user/student1.jpg");
                setSchool("学校未知");
            }});
            return ResponseWrapper.markCustomSuccess("注册成功！请登录");
        }if (param.getRoleAid().equals(2)){
            // 企业注册
            Enterprise company = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().orderByDesc(Enterprise::getAid).last("limit 1"));
            Integer addCompanyAid = company.getAid() + 1;
            enterpriseMapper.insert(new Enterprise(){{
                setAid(addCompanyAid);
                setName(param.getName());
                setPassword(MD5Tool.getMD5(param.getPassword()));
                setAccountNumber(param.getAccount());
                setLeader("企业联系人未知");
                setPhone(param.getPhone());
                setEmail(param.getEmail());
                setAddress("企业地址未知");
                setAvatar("https://recruitment-files.oss-cn-chengdu.aliyuncs.com/company/companyAvatar.jpg");
                setIntroduction("简介暂无");
                setBgImage("https://recruitment-files.oss-cn-chengdu.aliyuncs.com/company/company_bg01.jpg");
                setEmployeeCount(10);
            }});
            return ResponseWrapper.markCustomSuccess("注册成功！请登录");
        }else {
            return ResponseWrapper.markCustomError("注册失败！");
        }
    }

    @Override
    public ResponseWrapper getCurrentLoginName(GetCurrentLoginNameParam param) {
        if (param.getAccount() == null){
            return ResponseWrapper.markSuccess(null);
        }else {
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
            if (user != null){
                return ResponseWrapper.markSuccess(user.getName());
            }else {
                Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, param.getAccount()));
                return ResponseWrapper.markSuccess(enterprise.getName());
            }
        }
    }

    /**
     * 通过登陆的账号获取当前角色名称
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper getCurrentLoginRoleName(GetCurrentLoginRoleNameParam param) {
        GetCurrentLoginRoleNameResult result = new GetCurrentLoginRoleNameResult();
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
        if (user != null){
            if (user.getIsAdmin()==1){
                result.setRemarks("管理员");
            }
            if (user.getIsAdmin()==0){
                result.setRemarks("用户");
            }
        }else {
            Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, param.getAccount()));
            if (enterprise != null){
                result.setRemarks("企业");
            }
        }
        return ResponseWrapper.markSuccess(result);
    }

    /**
     * 查询注册输入的账号是否相同
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper checkAccountApi(CheckAccountApiParam param) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
        if (user != null){
            return ResponseWrapper.markSuccess(true);
        }else {
            Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, param.getAccount()));
            if (enterprise != null){
                return ResponseWrapper.markSuccess(true);
            }else {
                return ResponseWrapper.markSuccess(false);
            }
        }
    }

    /**
     * 注册时检查手机号是否存在
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper checkPhoneIsExist(ChenkPhoneIsExist param) {
        List<User> users = userMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getPhone, param.getPhone()));
        if(users.size() > 0){
            return ResponseWrapper.markSuccess(true);
        }else {
            List<Enterprise> enterprises = enterpriseMapper.selectList(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getPhone, param.getPhone()));
            if (enterprises.size() > 0){
                return ResponseWrapper.markSuccess(true);
            }else {
                return ResponseWrapper.markSuccess(false);
            }
        }
    }
}
